import hashlib
from django.shortcuts import render
from django.http import HttpResponse

from Puer.publicUtils.public_method import get_page_start_end, delivery_company_transform
from models import *
from Puer.constant import constant
import json
import traceback
from django.db import transaction
import datetime
from xml.etree import ElementTree as ET
import urllib.request
import random
import string
import time
import requests
from collections import Iterable


# 订单中心
def all_orders(request):
    get_user_id = request.GET.get('userId')
    try:
        # 代上门
        wait_orders = Orders.objects.filter(userid=get_user_id, status=constant.OVERHANG)
        data1 = []
        for order in wait_orders:
            order_details = Orderdetail.objects.filter(orderid=order.orderid)

            for order_detail in order_details:
                product = Product.objects.get(productid=order_detail.productid)
                dic1 = {
                    "name": product.name,
                    'product_id': product.productid,
                    'thumbnail': '%s%s' % (constant.FILE_ADDRESS, product.thumbnail),
                    'price': "%.2f" % float(product.price),
                    'number': order_detail.number,
                    'time': order.date.strftime('%Y-%m-%d')
                }

                data1.append(dic1)

        # 待收货
        recv_orders = Orders.objects.filter(userid=get_user_id, status=constant.WAITRECV)
        data2 = []
        for order in recv_orders:
            order_details = Orderdetail.objects.filter(orderid=order.orderid)

            for order_detail in order_details:
                product = Product.objects.get(productid=order_detail.productid)
                dic1 = {
                    "order_id": order.orderid,
                    "name": product.name,
                    'product_id': product.productid,
                    'thumbnail': '%s%s' % (constant.FILE_ADDRESS, product.thumbnail),
                    'price': "%.2f" % float(product.price),
                    'time': order.date.strftime('%Y-%m-%d'),
                    'number': order_detail.number
                }

                data2.append(dic1)

        # 完成
        finish_orders = Orders.objects.filter(userid=get_user_id, status=constant.FINISH)
        data3 = []
        for order in finish_orders:
            order_details = Orderdetail.objects.filter(orderid=order.orderid)

            for order_detail in order_details:
                product = Product.objects.get(productid=order_detail.productid)
                dic1 = {
                    "name": product.name,
                    'product_id': product.productid,
                    'thumbnail': '%s%s' % (constant.FILE_ADDRESS, product.thumbnail),
                    'price': "%.2f" % float(product.price),
                    'number': order_detail.number,
                    'time': order.date.strftime('%Y-%m-%d')
                }

                data3.append(dic1)

        # 全部
        finish_orders = Orders.objects.filter(userid=get_user_id)
        data4 = []
        for order in finish_orders:
            order_details = Orderdetail.objects.filter(orderid=order.orderid)

            for order_detail in order_details:
                product = Product.objects.get(productid=order_detail.productid)
                dic1 = {
                    "name": product.name,
                    'product_id': product.productid,
                    'thumbnail': '%s%s' % (constant.FILE_ADDRESS, product.thumbnail),
                    'price': "%.2f" % float(product.price),
                    'number': order_detail.number,
                    'time': order.date.strftime('%Y-%m-%d')
                }

                data4.append(dic1)

        data = {
            'overhang': data1,
            'waitrecv': data2,
            'finish': data3,
            'all': data4
        }


    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 是否含有地址
def is_address_default(request):
    user_id = request.GET.get("userId")
    data = {
        "is_have_default_addr": True
    }
    user_address_result = Useraddress.objects.filter(userid=user_id, status=constant.USE)
    if not user_address_result:
        data["is_have_default_addr"] = False
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 直接购买
def pay_order(request):
    try:
        user_id = request.GET.get("userId")
        product_id = int(request.GET.get("productId"))
        user_address_res = Useraddress.objects.filter(userid=user_id, status=1)
        user_obj = Users.objects.get(userid=user_id)
        product_obj = Product.objects.get(productid=product_id)
        # 取用户默认地址，如果用户没有设置默认地址则从地址列表中返回一个地址
        for user_address_obj in user_address_res:
            if int(user_address_obj.addressdefault) == constant.YES:
                data = {
                    "address_id": user_address_obj.addressid,
                    "user_name": user_address_obj.name,
                    "user_phone": user_address_obj.phone,
                    "address": "%s%s" % (user_address_obj.city, user_address_obj.address),
                    "user_score": user_obj.userscore,
                    "product_thumbnail": "%s%s" % (constant.FILE_ADDRESS, product_obj.thumbnail)
                }
                break
            data = {
                "address_id": user_address_obj.addressid,
                "user_name": user_address_obj.name,
                "user_phone": user_address_obj.phone,
                "address": "%s%s" % (user_address_obj.city, user_address_obj.address),
                "user_score": user_obj.userscore,
                "product_thumbnail": "%s%s" % (constant.FILE_ADDRESS, product_obj.thumbnail)
            }
        return HttpResponse(json.dumps(data))
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 直接支付支付完成
@transaction.atomic
def pay_finish(request):
    try:
        get_user = request.GET.get("userId")
        # 支付订单id
        get_id = request.GET.get('Id')
        # 商品id
        get_product_id = int(request.GET.get('productId'))
        # 支付金额
        get_money = int(float(request.GET.get("money")) * 100)
        # 商品数量
        get_product_num = int(request.GET.get('number'))
        # 配送地址
        get_address = request.GET.get('address')
        # 手机号
        get_phone = request.GET.get('phone')
        # 联系人
        get_name = request.GET.get('name')
        # 尺寸
        get_size = request.GET.get('size')
        # 颜色
        get_color = request.GET.get('color')
        # 积分
        get_score = int(request.GET.get('score'))
        CreateNo = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + get_user
        jsons = "success"
        # 支付标识，0代表失败，1代表成功
        get_flag = int(request.GET.get('Flag'))
        product = Product.objects.get(productid=get_product_id)
        if get_product_num > product.stock:
            get_flag = 0
        pro = Productstandard.objects.filter(name=get_size, color=get_color, productid=get_product_id)
        if get_product_num > pro[0].stock:
            get_flag = 0
        if get_flag:
            # 支付成功
            # 查寻规格id
            standard = Productstandard.objects.filter(name=get_size, color=get_color)
            # 修改库存
            product.stock = product.stock - get_product_num
            product.save()
            # # 查询address
            # user_address = Useraddress.objects.filter(userid=get_user, addressid=get_address_id)

            Payorders.objects.filter(payorderid=get_id, status=constant.WAIT).update(status=constant.SUCCESS)
            if get_score:
                user = Users.objects.get(userid=get_user)
                user.userscore = user.userscore - get_score
                user.save()
            # 钱包明细
            Walletdetail.objects.create(
                userid=get_user,
                money=get_money,
                data=datetime.datetime.now(),
                kind=constant.CONSUME,
                remark=get_score
            )
            # 订单
            order = Orders.objects.create(
                orderid=CreateNo,
                userid=get_user,
                addressid=get_address,
                phone=get_phone,
                name=get_name,
                number=get_product_num,
                date=datetime.datetime.now(),
                # TODO 物流
                status=constant.OVERHANG,
                productname=product.name

            )
            # 订单详情
            Orderdetail.objects.create(orderid=order.orderid,
                                       standardid=standard[0].standardid,
                                       number=get_product_num,
                                       productid=get_product_id
                                       )
            # 修改规格里面的库存
            pro_standard = Productstandard.objects.get(productid=get_product_id, name=get_size, color=get_color)
            pro_standard.stock = pro_standard.stock - get_product_num
            pro_standard.save()
            # 查看自己是不是二级用户
            user_invite = Userinvite.objects.filter(userid=get_user)
            if user_invite:
                user = Users.objects.get(userid=user_invite[0].inviteid)
                user.userscore = user.userscore + get_money / 10
                user.save()

        else:
            # 支付取消
            Payorders.objects.filter(payorderid=get_id, status=1).update(status=3)
            # 支付失败或取消,关闭订单
            data = {}
            # 小程序appId
            wx_appid = 'wx035bbef893b394f5'
            # 支付商户号
            wx_mch_id = '1509037691'
            data['appid'] = 'wx035bbef893b394f5'
            data['mch_id'] = '1509037691'
            data['out_trade_no'] = get_id
            data['nonce_str'] = ''.join(
                [(string.ascii_letters + string.digits)[x] for x in random.sample(range(0, 62), 20)])
            count = 1
            test = ""
            for i in sorted(data.keys()):
                v = data.get(i)
                if count == 1:
                    test = test + '{key}={value}'.format(key=i, value=v)
                else:
                    test = test + '&{key}={value}'.format(key=i, value=v)
                count = count + 1
            test = test + '&key=Ydx20180818Ruitakesi17610106050X'
            sign = hashlib.md5(test.encode('utf-8')).hexdigest().upper()
            data['sign'] = sign
            xml = []
            for k in sorted(data.keys()):
                v = data.get(k)
                if k == 'detail' and not v.startswith('<![CDATA['):
                    v = '<![CDATA[{}]]'.format(v)
                xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
            get_data = '<xml>{}</xml>'.format(''.join(xml))

            req = urllib.request.Request('https://api.mch.weixin.qq.com/pay/closeorder')

            with urllib.request.urlopen(req, data=get_data.encode('utf-8')) as response:
                html = response.read().decode("utf8")
                response.close()
            tree = ET.fromstring(html)
            result = {}
            if tree.tag == 'xml':
                for child in tree:
                    result[child.tag] = child.text
            if result['return_code'] == 'SUCCESS' and result['result_code'] == 'SUCCESS':
                # 关闭成功
                pass
            else:
                # 关闭失败
                jsons = 'failure'

        return HttpResponse(jsons)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 购物车支付
@transaction.atomic
def pay_cart(request):
    try:
        get_cart_id_list = json.loads(request.GET.get('cartId'))
        get_user = request.GET.get('userId')
        get_id = request.GET.get('Id')
        # 总金额
        get_money = request.GET.get('money')
        # 配送地址
        get_address = int(request.GET.get('address'))
        # 积分
        get_score = int(request.GET.get('score'))
        # 手机号
        get_phone = request.GET.get('phone')
        # 联系人姓名
        get_name = request.GET.get('name')
        jsons = "success"
        # 支付标识，0代表失败，1代表成功
        get_flag = int(request.GET.get('Flag'))
        CreateNo = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + get_user
        # 订单表
        order = Orders.objects.create(
            orderid=CreateNo,
            userid=get_user,
            addressid=get_address,
            phone=get_phone,
            name=get_name,
            number=0,
            productname=[],
            date=datetime.datetime.now(),
            # TODO 物流
            status=constant.OVERHANG

        )
        # 钱包明细
        Walletdetail.objects.create(
            userid=get_user,
            money=get_money,
            date=datetime.datetime.now(),
            kind=constant.CONSUME,
            remark=get_score,

        )
        if get_score:
            user = Users.objects.get(userid=get_user)
            user.userscore = user.userscore - get_score
            user.save()

        if get_flag:
            # 支付成功
            Payorders.objects.filter(payorderid=get_id, status=constant.WAIT).update(status=constant.SUCCESS)
            name_list = []
            product_num = 0
            for cart_id in get_cart_id_list:

                shop_cart = Shoppingcart.objects.get(cartid=cart_id)
                # 商品id
                product_id = shop_cart.productid
                # 商品的数量
                num = shop_cart.number
                # 查寻规格id
                standard_id = shop_cart.standardid

                # 修改库存
                product = Product.objects.get(productid=product_id)
                product.stock = product.stock - num
                product.save()
                pro_standard = Productstandard.objects.get(standardid=standard_id)
                pro_standard.stock = pro_standard.stock - num
                pro_standard.save()
                # 查看自己是不是二级用户
                user_invite = Userinvite.objects.filter(userid=get_user)
                if user_invite:
                    user = Users.objects.get(userid=user_invite[0].inviteid)
                    user.userscore = user.userscore + get_money / 10
                    user.save()
                # 订单详情
                Orderdetail.objects.create(
                    orderid=order.orderid,
                    productid=product_id,
                    standardid=standard_id,
                    number=num
                )
                product_num += num
                name_list.append(
                    product.name
                )
            order.productname = str(name_list)
            order.number += product_num
            order.save()
        else:
            # 支付取消
            Payorders.objects.filter(payorderid=get_id, status=1).update(status=3)
            # 支付失败或取消,关闭订单
            data = {}
            # 小程序appId
            wx_appid = 'wx035bbef893b394f5'
            # 支付商户号
            wx_mch_id = '1509037691'
            data['appid'] = 'wx035bbef893b394f5'
            data['mch_id'] = '1509037691'
            data['out_trade_no'] = get_id
            data['nonce_str'] = ''.join(
                [(string.ascii_letters + string.digits)[x] for x in random.sample(range(0, 62), 20)])
            count = 1
            test = ""
            for i in sorted(data.keys()):
                v = data.get(i)
                if count == 1:
                    test = test + '{key}={value}'.format(key=i, value=v)
                else:
                    test = test + '&{key}={value}'.format(key=i, value=v)
                count = count + 1
            test = test + '&key=Ydx20180818Ruitakesi17610106050X'
            sign = hashlib.md5(test.encode('utf-8')).hexdigest().upper()
            data['sign'] = sign
            xml = []
            for k in sorted(data.keys()):
                v = data.get(k)
                if k == 'detail' and not v.startswith('<![CDATA['):
                    v = '<![CDATA[{}]]'.format(v)
                xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
            get_data = '<xml>{}</xml>'.format(''.join(xml))

            req = urllib.request.Request('https://api.mch.weixin.qq.com/pay/closeorder')

            with urllib.request.urlopen(req, data=get_data.encode('utf-8')) as response:
                html = response.read().decode("utf8")
                response.close()
            tree = ET.fromstring(html)
            result = {}
            if tree.tag == 'xml':
                for child in tree:
                    result[child.tag] = child.text
            if result['return_code'] == 'SUCCESS' and result['result_code'] == 'SUCCESS':
                # 关闭成功
                pass
            else:
                # 关闭失败
                jsons = 'failure'

        return HttpResponse(jsons)

    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 物流信息
def order_send_info(request):
    order_id = request.GET.get("Id")
    order_obj = Orders.objects.get(orderid=order_id)
    order_detail_result = Orderdetail.objects.filter(orderid=order_obj.orderid)
    company = order_obj.deliverycompany if order_obj.deliverycompany else constant.TO_BE_DELIVERED
    logistics_no = order_obj.deliveryno if order_obj.deliveryno else constant.TO_BE_DELIVERED
    order_product_name = ""
    product_thumbnail = ""
    logistics_details = []
    if order_detail_result:
        product_obj = Product.objects.get(productid=order_detail_result[0].productid)
        order_product_name = product_obj.name
        product_thumbnail = product_obj.thumbnail
    product = {
        "img": "%s%s" % (constant.FILE_ADDRESS, product_thumbnail),
        "name": order_product_name,
        # "standard": Productstandard.objects.filter(standardid=order_detail_result[0].standardid)[0].name,
        "no": logistics_no,
        "company": company,
        "time": order_obj.date.strftime("%Y-%m-%d %H:%M")
    }
    if company == constant.TO_BE_DELIVERED:
        # 没有物流信息
        return HttpResponse(json.dumps([product, []]), content_type='application/json')
    company_no = constant.DELIVERY_COMPANY[company]

    if order_obj.status == constant.WAITRECV:
        # 获取物流信息
        customer = "FA8F648C5B8D592FB236408C3E0FB77F"
        key = "AMpBLvQq7840"
        # 快递公司和快递编号
        param_string = '{"com":"' + str(company_no) + '","num":"' + str(logistics_no) + '"}'
        sign_data = param_string + key + customer
        sign = hashlib.md5(sign_data.encode("utf-8")).hexdigest().upper()
        data = {
            "param": param_string,
            "sign": sign,
            "customer": customer
        }
        req = 'https://poll.kuaidi100.com/poll/query.do'
        response = requests.post(req, data=data, verify=False)
        # 获取到的信息
        html = response.json()
        response.close()
        if "data" in html.keys():
            result = html["data"]
        elif "message" in html.keys():
            result = html["message"]
        if isinstance(result, Iterable):
            for item in result:
                row = {
                    "detail": item["context"],
                    "time": item["time"]
                }
                logistics_details.append(row)
    return HttpResponse(json.dumps([product, logistics_details]), content_type='application/json')


# 确认收货
def confirm_receipt(request):
    try:
        order_id = request.GET.get("orderId")
        user_id = request.GET.get("userId")
        Orders.objects.filter(orderid=order_id, userid=user_id, status=constant.WAITRECV).update(status=constant.FINISH,
                                                                                                 signintime=datetime.datetime.now())
        return HttpResponse("success")
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# -------------------------------------PC------------------------------


# 获取订单信息
def get_orders_info(request):
    try:
        get_page = request.GET.get("page")
        get_row = request.GET.get("row")
        # 手机号
        get_phone = request.GET.get("phone", None)
        # 商品名称
        get_product = request.GET.get("product", None)
        get_status = request.GET.get('status', None)
        # # 订单状态
        # get_order_status = orders_status_zh_mapping(request.GET.get("status"))
        # if get_order_status is constant.ALL:
        orders_result = Orders.objects.all().order_by("-date")
        # else:
        #     orders_result = Orders.objects.filter(status=get_order_status).order_by("-date")
        text = ['待上门', '待收货', '已完成', '已取消']
        if get_status:
            orders_result = Orders.objects.filter(status=int(get_status))
        if get_phone:
            orders_result = Orders.objects.filter(phone__contains=get_phone)
        if get_product:
            orders_result = Orders.objects.filter(productname__contains=get_product)
        if get_phone and get_product:
            orders_result = Orders.objects.filter(phone__contains=get_phone).filter(
                productname__contains=get_product).order_by("-date")
        if get_phone and get_status and get_status:
            orders_result = Orders.objects.filter(phone__contains=get_phone).filter(
                productname__contains=get_product).filter(status=int(get_status)).order_by("-date")
        if get_phone and get_status:
            orders_result = Orders.objects.filter(phone__contains=get_phone).filter(status=int(get_status)).order_by(
                "-date")
        if get_status and get_product:
            orders_result = Orders.objects.filter(
                productname__contains=get_product).filter(status=int(get_status)).order_by("-date")

        start, stop = get_page_start_end(get_page, get_row, orders_result)
        data = []
        data_count = len(orders_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            row = {
                # 订单编号
                'order_id': orders_result[count].orderid,
                # 收件人
                'receive': orders_result[count].name,
                # 用户手机号
                'phone': orders_result[count].phone,
                # 订单商品
                'product_name': orders_result[count].productname,
                # 商品数量
                'number': orders_result[count].number,
                # 订单时间
                'time': orders_result[count].date.strftime("%Y-%m-%d"),
                # 订单状态
                # 'status': orders_status_zh_mapping(int(orders_result[count].status)),
                'status': text[orders_result[count].status - 1]

            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 订单详情
def get_orders_details(request):
    try:
        get_order_id = request.GET.get("orderId")
        orders_result = Orders.objects.get(orderid=get_order_id)
        orders_for_userid = orders_result.userid if orders_result else None
        user_result = Users.objects.filter(userid=orders_for_userid)
        if len(user_result) != 1:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", "Error: user id conflict.", error_msg]),
                                content_type=constant.CONTENT_TYPE)
        # 订单详情信息
        orders_detail_result = Orderdetail.objects.filter(orderid=orders_result.orderid)
        order_date = orders_result.date.strftime("%Y-%m-%d")
        # 商品信息
        products_info = []

        for orders_detail in orders_detail_result:
            product_id = orders_detail.productid
            # 规格ID
            standard_id = orders_detail.standardid
            # 商品详情
            product_result = Product.objects.get(productid=product_id)
            # # 规格详情
            # product_standard_result = Productstandard.objects.get(standardid=standard_id)
            # 商品图
            product_thumbnail = "%s%s" % (constant.FILE_ADDRESS, product_result.thumbnail)

            products_info.append({
                # 商品编号
                'product_id': product_result.productid,
                # 商品名
                'product_name': product_result.name,
                'product_no': product_result.productno,
                # # 商品尺码
                # 'product_size': product_standard_result.name,
                # # 商品颜色
                # 'product_color': product_standard_result.color,
                # 商品图
                'product_thumbnail': product_thumbnail,
                # 下单时间
                'time': order_date
            })
        # 订单基本信息
        user_address = Useraddress.objects.filter(addressid=orders_result.addressid)
        data = {
            # 订单编号
            'order_id': orders_result.orderid,
            # 用户电话
            'user_phone': user_result[0].userphone,
            # 订单商品
            'product_name': orders_result.productname,
            # 订单数量
            'product_number': orders_result.number,
            # 下单时间
            'time': order_date,
            # 订单状态
            # 'status': orders_status_zh_mapping(int(orders_result.status)),
            'status': orders_result.status,
            # 物流编号
            'delivery_no': orders_result.deliveryno,
            # 物流公司
            'company': delivery_company_transform(orders_result.deliverycompany),
            # 收货人姓名
            'receive_name': orders_result.name,
            # 收货人手机号
            'receive_phone': orders_result.phone,
            # # 邮编
            # 'z_code': user_address[0].zipcode,
            # 收货地址
            'address': "%s,%s" % (user_address[0].city, user_address[0].address),
            # 商品信息
            'product': products_info
        }
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 订单收货人信息
def get_orders_receiver(request):
    try:
        data = []
        orders_id = request.GET.get("orderId")
        orders_result = Orders.objects.get(orderid=orders_id)
        if orders_result:
            data = {
                # 收货人姓名
                'name': orders_result.name,
                # 电话号码
                'phone': orders_result.phone,
                # 收货地址
                'address': orders_result.addressid
            }
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 更新收货人信息

def update_orders_receiver(request):
    try:
        orders_id = request.GET.get("orderId")
        receive_name = request.GET.get("name")
        receive_phone = request.GET.get("phone")
        receive_address = request.GET.get("address")
        order = Orders.objects.get(orderid=orders_id)
        order.name = receive_name
        order.phone = receive_phone
        order.addressid = receive_address
        order.save()

        return HttpResponse(json.dumps("success"), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 订单发货
def orders_to_be_delivered(request):
    try:
        order_id = request.GET.get("orderId")
        delivery_company = constant.DELIVERY_COMPANY[request.GET.get("company")]
        delivery_number = request.GET.get("no")
        # 更新订单状态
        # status = orders_status_zh_mapping(constant.PENDING_RECEIPT)
        try:
            Orders.objects.filter(orderid=order_id, status=constant.OVERHANG).update(deliverycompany=delivery_company,
                                                                                     deliveryno=delivery_number,
                                                                                     deliverytime=datetime.datetime.now(),
                                                                                     status=constant.WAITRECV)
        except:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", "Error: Update Orders failure.", error_msg]),
                                content_type=constant.CONTENT_TYPE)

        return HttpResponse(json.dumps("success"), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
